import React from 'react';
import { ChatMessage } from '../hooks/useChatStream';
import MarkdownText from './MarkdownText';
import CommandOutput from './CommandOutput';
import CommandStep from './CommandStep';

const AssistantMessage: React.FC<{ message: ChatMessage }> = ({ message }) => {
  const time = new Date(message.timestamp).toLocaleTimeString();
  const contents = message.contents || [{ type: 'text', text: message.content }];

  const renderContents = () => {
    const nodes: React.ReactNode[] = [];
    let textBuffer: React.ReactNode[] = [];

    const flushText = () => {
      if (textBuffer.length > 0) {
        nodes.push(
          <div className="bubble" key={`text-group-${nodes.length}`}>
            {textBuffer}
          </div>
        );
        textBuffer = [];
      }
    };

    for (let i = 0; i < contents.length; i++) {
      const c = contents[i];

      if (c.type === 'command') {
        flushText();
        const outputs: string[] = [];
        let j = i + 1;
        while (j < contents.length && contents[j].type === 'output') {
          outputs.push(contents[j].text);
          j++;
        }
        nodes.push(
          <CommandStep
            key={`cmd-${i}`}
            command={c.text}
            output={outputs.join('\n')}
          />
        );
        i = j - 1;
        continue;
      }

      if (c.type === 'output') {
        flushText();
        nodes.push(<CommandOutput key={`out-${i}`} text={c.text} />);
        continue;
      }

      if (c.type === 'thinking' || c.type === 'system') {
        const text = (c.text || '').trim();
        if (text.length === 0) {
          continue;
        }
        flushText();
        nodes.push(
          <div
            key={`sys-${i}`}
            className={`bubble system-bubble${c.type === 'thinking' ? ' thinking-bubble' : ''}`}
          >
            <MarkdownText text={text} />
          </div>
        );
        continue;
      }

      if (c.type === 'text') {
        const text = (c.text || '').trim();
        if (text.length === 0) {
          continue;
        }
        if (c.sayType === 'completion_result') {
          // 最终结果：单独高亮气泡
          flushText();
          nodes.push(
            <div className="bubble result-bubble" key={`result-${i}`}>
              <MarkdownText text={text} />
            </div>
          );
        } else {
          textBuffer.push(<MarkdownText key={`text-${i}`} text={text} />);
        }
        continue;
      }

      nodes.push(
        <div key={`raw-${i}`} style={{ whiteSpace: 'pre-wrap' }}>
          {c.text}
        </div>
      );
    }
    flushText();
    return nodes;
  };

  return (
    <div className="msg ai">
      <div>
        {renderContents()}
        {message.isStreaming && (
          <div style={{ opacity: 0.6, marginTop: 4, fontSize: 12, color: '#8c8c8c' }}>
            生成中...
          </div>
        )}
        <div className="timestamp">{time}</div>
      </div>
    </div>
  );
};

export default AssistantMessage;
